package com.witmore.skyline.web.exception;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class StackTraceFilter {

    private final String[] projectPackages = {
            "com.witmore.skyline"
    };

    /**
     * 判断堆栈行是否属于项目代码
     */
    private boolean isProjectStackTraceLine(String stackTraceLine) {
        // 保留异常描述行(第一行)
        if (!stackTraceLine.trim().startsWith("at ")) {
            return true;
        }

        // 检查是否包含项目包名前缀
        return Arrays.stream(projectPackages)
                .anyMatch(pkg -> stackTraceLine.contains("at " + pkg));
    }

    /**
     * 获取简化的堆栈跟踪(最多5行项目相关堆栈)
     */
    public String getSimplifiedStackTrace(Throwable e) {
        String fullStackTrace = ExceptionUtils.getStackTrace(e);
        String[] lines = fullStackTrace.split("\n");

        // 保留第一行异常信息
        StringBuilder result = new StringBuilder(lines[0]).append("\n");

        int projectStackCount = 0;
        for (int i = 1; i < lines.length && projectStackCount < 5; i++) {
            if (isProjectStackTraceLine(lines[i])) {
                result.append(lines[i]).append("\n");
                projectStackCount++;
            }
        }
        return result.toString();
    }
}